<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->
<template>
  <div class="Mall4j body page-chat">
    <div class="message-box">
      <div class="left">
        消息盒子
      </div>
      <div class="right">
        {{ titleName }}
        <span :class="[ lineStatus ? 'in' : 'out']">{{ lineStatus?'(在线)':'(离线)' }}</span>
      </div>
    </div>
    <div class="chat-box">
      <!-- 消息盒子左侧栏 -->
      <chatBoxLeft
        :on-select-channel="onSelectChannel"
        :current-shop-id="currentShopId"
        :chat-type="chatType"
        @channel-info-update="channelInfoUpdate"
      />
      <!-- 消息盒子右侧信息回复栏 -->
      <div class="chat-box-right">
        <div
          v-if="shopList[totalUserUnreadsIndex]"
          class="shop-name-tittle"
        >
          {{ chatType === 1 ? $t('chat.mallCustomerService') : shopName }}
          <span :class="['shopStatus', shopList[totalUserUnreadsIndex].isOnline?'in':'out']">
            {{ shopList[totalUserUnreadsIndex].isOnline ? $t('chat.onLine') : $t('chat.offLine') }}
          </span>
        </div>
        <div class="im-box">
          <div class="im-main">
            <div class="chat-main-form">
              <div class="display-infor">
                <div
                  ref="chatRef"
                  class="message-list"
                  @scroll="handleScroll"
                >
                  <template
                    v-for="(m, index) in messages"
                    :key="index"
                  >
                    <!-- 用户发送的消息 -->
                    <div
                      v-if="m.timeStr"
                      class="topTime"
                    >
                      {{ m.timeStr }}
                    </div>
                    <div
                      v-if="m.send"
                      :id="m.clientMsgNo"
                      class="message right"
                    >
                      <div style="display: flex; justify-content: flex-end;">
                        <div class="read-status">
                          <div
                            v-if="maxReadSeq>=m.messageSeq"
                          >
                            已读
                          </div>
                          <div
                            v-else
                          >
                            未读
                          </div>
                        </div>
                        <div class="bubble right">
                          <div
                            v-if="m.content.text?.msgType===1"
                            class="bubble-content"
                          >
                            {{ getMessageText(m) }}
                          </div>

                          <div
                            v-if="m.content.text?.msgType===2"
                            class="bubble-content"
                            @tap="showPic(checkFileUrl(m.content.text.msg))"
                          >
                            <el-image
                              :src="checkFileUrl(m.content.text.msg)"
                              class="longimage"
                              :preview-src-list="[checkFileUrl(m.content.text.msg)]"
                            />
                          </div>
                          <!-- 订单链接 -->
                          <div
                            v-if="m.content.text?.msgType===4"
                            class="prod-link"
                          >
                            <div
                              v-if="m.content.text.msg.orderFlag"
                              class="prod-number"
                              @click="toProdDetail(m.content.text.msg,1)"
                            >
                              {{ $t('orderNumberT') }}:{{ m.content.text.msg.orderNumber }}
                            </div>
                            <div
                              class="link-prod prod-no"

                              @click="toProdDetail(m.content.text.msg,m.content.text.msg.orderFlag ? 1 : 0,m.content.text.msg.orderType)"
                            >
                              <img-show
                                :src="m.content.text.msg.imgs"
                                alt=""
                              />
                              <div class="link-detail">
                                <div class="prod-name">
                                  {{ m.content.text.msg.prodName }}
                                </div>
                                <div class="prod-price">
                                  <span>
                                    {{ m.content.text.msg.actualTotal ? '￥' : '' }}
                                    {{ m.content.text.msg.actualTotal ? m.content.text.msg.actualTotal : '' }}
                                    {{ (m.content.text.msg.actualTotal && m.content.text.msg.useScore) ? '+' : '' }}
                                    <span v-if="m.content.text.msg.useScore">
                                      {{ m.content.text.msg.useScore }} {{ $t('prodDetail.points') }}
                                    </span>
                                  </span>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>

                        <div class="avatar">
                          <img
                            :src="getChannelInfo(m,'pic')?checkFileUrl(getChannelInfo(m,'pic')):imUserImg"
                          >
                        </div>
                      </div>
                    </div>
                    <!-- 用户发送的消息end -->
                    <!-- 商家-平台发送的消息 -->
                    <div
                      v-if="m.send===false"
                      :id="m.clientMsgNo"
                      class="message"
                    >
                      <div class="username">
                        {{ getChannelInfo(m,'nickName') }}
                      </div>
                      <div style="display: flex; max-width: 70%;">
                        <div class="avatar">
                          <img
                            :src="channelInfo.logo?checkFileUrl(channelInfo.logo):imAvatarPng"
                          >
                        </div>
                        <div
                          class="bubble-left"
                        >
                          <div
                            v-if="m.content.text?.msgType===2"
                            @tap="showPic(checkFileUrl(m.content.text.msg))"
                          >
                            <el-image
                              :src="checkFileUrl(m.content.text.msg)"
                              class="longimage"
                              :preview-src-list="[checkFileUrl(m.content.text.msg)]"
                            />
                          </div>
                          <div
                            v-if="(m.content.text?.msgType===-1||m.content.text?.msgType===1||m.content.text?.type===-5)&&m.content.text?.type!==-1"
                            class="text"
                          >
                            {{ m.content.text.msg }}
                          </div>
                          <div
                            v-if="m.content.text?.type===-1"
                            class="text"
                          >
                            <div
                              v-if="m.content.text.sendTextState"
                            >
                              {{ m.content.text.content }}
                            </div>

                            <div
                              v-if="m.content.text.sendIssusState"
                            >
                              <el-button
                                v-for="item in m.content.text.issues"
                                :key="item.id"
                                style="display: block;padding-left: 0px; margin-left: 0px;"
                                type="primary"
                                link
                                @click="sendIssues(item.content,item.issues,m.channel.channelID)"
                              >
                                • {{ item.issues }}
                              </el-button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- 商家-平台发送的消息end -->

                    <!-- 发送链接 -->
                    <div
                      v-if=" m.content.text?.prodInfo?.msgType === 3 "
                      class="link-box"
                    >
                      <div
                        v-if="m.content.text?.prodInfo.orderFlag"
                        class="prod-number"
                        @click="toProdDetail(m.content.text.prodInfo,1)"
                      >
                        {{ $t('chat.orderNumber') }}：{{ m.content.text?.prodInfo.orderNumber }}
                      </div>
                      <div
                        class="link-prod"
                        @click="toProdDetail(m.content.text.prodInfo,0,m.content.text?.prodInfo.orderType)"
                      >
                        <img-show
                          :src="m.content.text?.prodInfo.imgs"
                          alt=""
                        />
                        <div class="link-detail">
                          <div class="prod-name">
                            {{ m.content.text?.prodInfo.prodName }}
                          </div>
                          <span>
                            {{ m.content.text?.prodInfo.actualTotal ? '￥' : '' }}
                            {{ m.content.text?.prodInfo.actualTotal ? m.content.text?.prodInfo.actualTotal : '' }}
                            {{ (m.content.text?.prodInfo.actualTotal && m.content.text?.prodInfo.useScore) ? '+' : '' }}
                            <span v-if="m.content.text?.prodInfo.useScore">
                              {{ m.content.text?.prodInfo.useScore }} {{ $t('prodDetail.points') }}
                            </span>
                          </span>
                        </div>
                      </div>
                      <div
                        class="link-send"
                        @click="sendText(2,m.content.text.prodInfo)"
                      >
                        {{ $t('chat.sendLink') }} <i class="link-send-right" />
                      </div>
                    </div>
                  </template>
                </div>
              </div>
              <div class="reply">
                <div class="upload" />
                <label
                  for="iii"
                  class="imgUp"
                ><a
                  class="upload"
                  style="cursor: pointer"
                /></label>
                <input
                  id="iii"
                  ref="fileRef"
                  accept="image/png, image/jpeg"
                  type="file"
                  class="search-btnn"
                  @change="toolEvent"
                >
                <div class="reply-area">
                  <textarea
                    id=""
                    v-model="textMsg"
                    name=""
                    cols="20"
                    rows="4"
                    @keydown="messageSendlisten($event)"
                  />
                </div>

                <div
                  class="send"
                  @click="sendText(1)"
                >
                  {{ $t('chat.send') }}
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧我的浏览和我的订单栏 -->
          <div class="order-column">
            <div class="tab-switch">
              <span
                :class="['inquiry', tabIndex ? '' : 'active']"
                @click="tabSwitch(0)"
              >{{ $t('chat.recentlyViewed') }}</span>
              <span
                :class="['my-order', !tabIndex ? '' : 'active']"
                @click="tabSwitch(1)"
              >{{ $t('chat.myOrders') }}</span>
            </div>
            <ul
              v-show="!tabIndex"
              class="recent-list"
            >
              <li
                v-for="(recent,index) in reBrowseList"
                :key="index"
                class="prod-item"
              >
                <img-show
                  :src="recent.pic"
                  :class-list="['prod-img']"
                />
                <div class="prod-detail">
                  <div
                    class="prod-name"
                    @click="toProdDetail(recent,0,recent.orderType)"
                  >
                    {{ recent.prodName }}
                  </div>
                  <div class="prod-b">
                    <div class="prod-price">
                      ￥{{ recent.price }}
                    </div>
                    <div
                      class="prod-send"
                      @click="sendText(3, recent)"
                    >
                      {{ $t('chat.send') }}{{ $t('products') }}
                    </div>
                  </div>
                </div>
              </li>
              <div
                v-if="!noMoreRe"
                class="bottom-tips"
              >
                {{ $t('chat.noRecord') }}
              </div>
            </ul>

            <!-- 我的订单 -->
            <ul
              v-show="tabIndex"
              v-infinite-scroll="scrollOrderList"
              class="order-list"
              infinite-scroll-disabled="disabled"
              @scroll="showNoMore = true"
            >
              <li
                v-for="(item, index) in orderList"
                :key="index"
                class="prod-item botl"
                :style="{
                  paddingBottom: item.orderItemDtos.length <= 1 ? '18px' : '0',
                }"
              >
                <div class="order-number">
                  <span
                    class="number"
                    @click="toProdDetail(item,1)"
                  >{{ $t('chat.orderNumber') }}: {{ item.orderNumber }}</span>
                </div>
                <div
                  v-for="(prod, prodIndex) in item.orderItemDtos"
                  :key="prodIndex"
                  class="order-box"
                  :style="{
                    paddingBottom: item.orderItemDtos.length > 1 ? '20px' : '0',
                  }"
                >
                  <div
                    class="prod-box"
                  >
                    <img-show
                      :src="prod.pic"
                      class="prod-img"
                    />
                    <div class="prod-detail">
                      <div class="prod-name">
                        {{ prod.prodName }}
                      </div>
                      <div class="prod-b">
                        <div class="prod-price">
                          ￥{{ item.orderType===3? item.actualTotal :prod.actualTotal }}
                          {{ (item.actualTotal && item.userScore) ? '+' : '' }}
                          <span v-if="item.userScore">
                            {{ item.userScore }} {{ $t('prodDetail.points') }}
                          </span>
                        </div>
                        <div
                          class="prod-send"
                          @click="sendText(4, prod, item.orderType,item.actualTotal)"
                        >
                          {{ $t('chat.send') }}{{ $t('products') }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="gift-group">
                    <div
                      v-for="(orderGift, giftIndex) in prod.giveawayList"
                      :key="giftIndex"
                      class="gift-item"
                    >
                      <div class="giveaway-item-name">
                        【{{ $t('prodDetail.gift') }}】 {{ orderGift.prodName }}
                      </div>
                      <div class="giveaway-item-sku-count">
                        x{{ orderGift.prodCount }}
                      </div>
                    </div>
                  </div>
                </div>
              </li>
              <p
                v-if="loading"
                class="bottom-tips"
              >
                {{ $t('chat.loading') }}...
              </p>
              <p
                v-else-if="showNoMore && noMore&&orderList&&orderList.length>0"
                class="bottom-tips"
              >
                {{ $t('chat.noMore') }}
              </p>
              <p
                v-else-if="noMore&&!(orderList&&orderList.length>0)"
                class="bottom-tips"
              >
                {{ $t('chat.noRecord') }}
              </p>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 重新登录提示弹窗 -->
    <div
      v-if="isPopup"
      class="login-baBox"
    >
      <div class="popup-box">
        <div class="tit">
          <div class="text">
            {{ $t('tips') }}
          </div>
          <div
            class="close"
          />
        </div>
        <div class="con">
          <div class="tip">
            <div class="tip-info">
              <div class="result">
                {{ $t('chat.pleaseLoginAgain') }}
              </div>
              <div
                class="btns"
                style="justify-content: center"
              >
                <a
                  href="JavaScript:"
                  class="btn-r"
                  @click="goToLogin()"
                >{{ $t('register.goToLogin') }}</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as util from '@/utils/index.js'
import Cookie from 'vue-cookies'
import imAvatarPng from '@/assets/images/chat/imAvatar.png'
import imUserImg from '@/assets/images/chat/userImg.jpg'
import { ElMessage } from 'element-plus'
import { ConnectStatus, WKSDK, Message, Channel, PullMode, Setting, MessageText, ChannelTypeGroup, MessageStatus } from 'wukongimjssdk'
import chatBoxLeft from './components/Conversation/index.vue'
import { Convert } from './components/Conversation/convert'
import { checkFileUrl } from '@/utils/index.js'
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const userId = ref(userStore.userId)

let orderCurrent = 1 // 我的订单当前页
let orderPages = 1 // 我的订单
const noMore = computed(() => {
  return orderCurrent >= orderPages
})

const reBrowseList = ref([]) // 最近浏览列表
const noMoreRe = computed(() => {
  return reBrowseList.value.length > 0
})

const isPopup = ref(false) // 显示登录弹窗
const userImg = ref(null)
const userName = ref(null)
const currentShopId = ref(null) // 商家id
const chatType = ref(null)

onMounted(async () => {
  if (!Cookie.get('bbcToken') || !userStore.nickName) {
    isPopup.value = true
    return
  }
  userName.value = userStore.nickName
  // json格式转换，应对图片为null时出现的判断失效
  userImg.value = userStore.userAvatar
  currentShopId.value = Number(route.query.shopId)
  chatType.value = Number(route.query.chatType)
  getSensitiveWords()
  document.title = $t('chat.onlineCustomerService')
  getWukong()
  WKSDK.shared().chatManager.addCMDListener(cmdListener) // 监听cmd消息
})
bus.on('showLogin', msg => {
  isPopup.value = msg
})

const showNoMore = ref(false) // showNoMore  是否显示
const tabIndex = ref(0) // 0 正在浏览 1我的订单
/**
 * 最近浏览我的订单tab切换
 */
const tabSwitch = (status) => {
  tabIndex.value = status
  if (status === 1) {
    getOrderList(shopId) // 我的订单
  }
}

const shopList = ref([])
const shopName = ref(null)
const totalUserUnreadsIndex = ref(0) // 选中的店家下标
const orderList = ref([])
const loading = ref(false)
const fileRef = ref(null)
let selectFileObj = null // 上传图片对象
// 发送图片
const toolEvent = () => {
  if (shopStatus === 2 || shopStatus === 3 || shopStatusArr.includes(shopId)) {
    ElMessage.warning('商家下线')
    return
  }
  WKSDK.shared().chatManager.removeMessageStatusListener(messageStatusListener)
  if (fileRef.value.files[0]) {
    selectFileObj = fileRef.value.files[0]
  }
  if (selectFileObj) {
    http({
      url: '/p/file/getPreSignUrl',
      method: 'get',
      params: {
        fileName: selectFileObj.name,
        isImFile: true
      }
    }).then(async ({ data }) => {
      await uploadFile(data.preSignUrl, selectFileObj).then(() => {
        http({
          url: '/p/file/uploadSuccess',
          method: 'put',
          data: [
            {
              fileId: data.fileId,
              attachFileGroupId: 0,
              fileSize: selectFileObj.size
            }
          ]
        }).then(() => {
          // 解决上传同一图片不显示bug
          if (fileRef.value) {
            fileRef.value = null
          }
          const msgObj = JSON.stringify({ msg: data.filePath, msgType: 2 })
          const content = new MessageText(msgObj)
          WKSDK.shared().chatManager.send(content, to.value)
          scrollBottom()
        })
      })
    })
  }
}

/**
 * 链接点击去往商品详情
 */
const toProdDetail = (prodInfo, type, orderType) => {
  // type 1 点击订单跳转 type
  let routeUrl = null
  if (Cookie.get('bbcToken')) {
    if (type) {
      routeUrl = router.push({
        path: '/order-detail',
        query: {
          orderNumber: prodInfo.orderNumber
        }
      })
    } else if (orderType === 2) {
      // 秒杀商品
      // 秒杀商品活动是否结束
      http.get('/p/seckill/prod', {
        params: {
          prodId: prodInfo.prodId
        }
      }).then(({ data }) => {
        if (data) {
          const newPage = router.resolve({ path: '/detail', query: { prodId: prodInfo.prodId } })
          window.open(newPage.href, '_blank', 'noopener,noreferrer')
        } else {
          ElMessage.warning($t('spike.currentSecondsAreOver'))
        }
      })
    } else {
      const query = orderType !== 3 ? { prodId: prodInfo.prodId } : { prodId: prodInfo.prodId, scoreFee: prodInfo.useScore }
      routeUrl = router.resolve({ path: '/detail', query })

      http.get('/prod/prodInfo', {
        params: {
          prodId: prodInfo.prodId,
          userId: userId.value
        }
      }).then(() => {
        window.open(routeUrl.href, '_blank', 'noopener,noreferrer')
      })
    }
  }
}

/**
 * 进行相隔时间判断
 * true 删除显示时间
 * false 保留显示时间
 */
const timeBeApart = (uppTime, preTime) => {
  if (!uppTime) {
    return false
  }
  const dateDiff = preTime - uppTime// 时间差的毫秒数
  const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))// 计算出相差天数
  const leave1 = dateDiff % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
  const hours = Math.floor(leave1 / (3600 * 1000))// 计算出小时数
  // 计算相差分钟数
  const leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
  const minutes = Math.floor(leave2 / (60 * 1000))// 计算相差分钟数

  return !(dayDiff >= 1 || hours >= 1 || minutes > 4)
}

/**
 * 滚动加载订单
 */
const scrollOrderList = () => {
  orderCurrent += 1
  if (orderCurrent > orderPages) {
    loading.value = true
  } else {
    getOrderList(shopId)
    loading.value = false
  }
}

/**
 * 账号下线前往登录
 */
const goToLogin = () => {
  Cookie.remove('bbcToken')
  router.push('/login')
  isPopup.value = false
}

const getSensitiveWords = () => {
  http.get('/webConfig/info/SENSITIVE_WORDS').then(({ data }) => {
    data = JSON.parse(data)
    if (data?.sensitiveWord) {
      sensitiveWords = data.sensitiveWord.replaceAll('，', '|')
    }
  })
}
const sendAutoReply = () => {
  setTimeout(() => {
    http.post('/p/wuKongIm/sendAutoReply?channelId=' + to.value.channelID) // 让用户的信息先发送于自动回复
  }, 1000)
}

const title = ref('')
let connectStatusListener
let messageListener
let sendStatus = false
const channelInfolineStatus = ref(false)
const getWukong = () => {
  http.post('/p/wuKongIm/registerOrLogin?token=' + Cookie.get('bbcToken')).then(({ data }) => {
    // 认证信息
    const config = WKSDK.shared().config
    config.addr = import.meta.env.VITE_APP_WS_IM_API
    config.uid = data.uid // 用户uid（需要在悟空通讯端注册过）
    config.token = data.token// 用户token （需要在悟空通讯端注册过）
    config.debug = true
    config.deviceFlag = 0
    WKSDK.shared().config = config
    WKSDK.shared().connect()

    // 监听连接状态
    connectStatusListener = (status) => {
      if (status === ConnectStatus.Connected) {
        title.value = '(连接成功)'
      } else {
        title.value = '(断开)'
      }
    }
    WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener)
    // 监听消息
    messageListener = async (msg) => {
      msg.messageSeq = ++lastMessageSeq // 新发送的消息没有序列号,此处添加序列号
      http.post('/p/wuKongIm/conversations/setUnread', { channel_id: to.value.channelID, maxSeq: lastMessageSeq })
      if (msg.send) { // 自动回复
        http.post('/p/wuKongIm/getShopChannelInfo?shopId=' + shopId).then(({ data: data2 }) => {
          sendAutoReplyStatus = data2.imChannel.sendAutoReply
          if ((lineStatus.value === 0 || !channelInfolineStatus.value) && sendAutoReplyStatus === 0) {
            sendAutoReply()
          }
        })
        if (sendStatus) {
          sendAutoReply()
          sendStatus = false
        }
      }
      if (!to.value.isEqual(msg.channel)) {
        return
      }
      if (messages.value.length) {
        const prevTime = util.tsToDate(
          messages.value[messages.value.length - 1].timestamp * 1000,
          'M月D日 h:m'
        )
        const nowTime = util.tsToDate(new Date().getTime(), 'M月D日 h:m')
        if (prevTime.slice(0, prevTime.indexOf(' ')) === nowTime.slice(0, nowTime.indexOf(' '))) {
          msg.timeStr = util.tsToDate(new Date().getTime(), 'h:m')
        } else {
          msg.timeStr = util.tsToDate(new Date().getTime(), 'M月D日 h:m')
        }
        const timeFlag = timeBeApart(messages.value[messages.value.length - 1].timestamp * 1000, new Date().getTime())
        if (timeFlag) {
          delete msg.timeStr
        }
      } else {
        msg.timeStr = util.tsToDate(new Date().getTime(), 'M月D日 h:m')
      }
      messages.value.push(msg)
      scrollBottom()
    }
    WKSDK.shared().chatManager.addMessageListener(messageListener)
  })
}
const isJSON = (str) => {
  if (typeof str == 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}
/**
 * textarea回车事件
 */
const messageSendlisten = (event) => {
  if (event.keyCode === 13) {
    sendText(1) // 发送文本
    event.preventDefault() // 阻止浏览器默认换行操作
    return false
  }
}

let sensitiveWords = '' // 敏感词
const textMsg = ref(null) // 用户输入内容
/**
 * 发送消息
 */
const scrollBottom = () => {
  const chat = chatRef.value
  if (chat) {
    nextTick(function () {
      chat.scrollTop = chat.scrollHeight
    })
  }
}
// eslint-disable-next-line no-unused-vars
const sendText = (type, prod, orderType, actualTotal) => {
  if (shopStatus === 2 || shopStatus === 3 || shopStatusArr.includes(shopId)) {
    ElMessage.warning('商家已下线')
    return
  }
  WKSDK.shared().chatManager.removeMessageStatusListener(messageStatusListener)
  // type 1 = 发送消息  type 2 = 发送商品链接  type 3 = 右侧我的订单发送  type 4 = 发送订单号
  if (type === 1) {
    if (textMsg.value === '' || textMsg.value.match(/^\s+$/)) {
      ElMessage.warning('不能发送空白消息哦')
      return
    }
    if (sensitiveWords) {
      try {
        const rep = new RegExp(sensitiveWords, 'g')
        textMsg.value = textMsg.value.replaceAll(rep, '**')
      } catch (e) {}
    }
    let content = ''

    const msgObj = JSON.stringify({ msg: textMsg.value, msgType: 1 })
    content = new MessageText(msgObj)
    WKSDK.shared().chatManager.send(content, to.value)
    textMsg.value = ''
  }
  const product = prod ? JSON.parse(JSON.stringify(prod)) : null // 避免接下来的操作改变原数组
  if (type === 2) {
    product.actualTotal = product.price
    const msgObj = JSON.stringify({ msg: product, msgType: 4 })
    const content = new MessageText(msgObj)
    WKSDK.shared().chatManager.send(content, to.value)
  }
  if (type === 3) {
    product.imgs = product.pic
    product.actualTotal = product.price
    const msgObj = JSON.stringify({ msg: product, msgType: 4 })
    const content = new MessageText(msgObj)
    WKSDK.shared().chatManager.send(content, to.value)
  }
  if (type === 4) {
    product.imgs = product.pic
    product.orderFlag = true
    product.orderType = orderType
    product.actualTotal = actualTotal
    const msgObj = JSON.stringify({ msg: product, msgType: 4 })
    const content = new MessageText(msgObj)
    WKSDK.shared().chatManager.send(content, to.value)
  }
  scrollBottom()
}
const to = ref(new Channel('', ChannelTypeGroup)) // 对方的频道信息
const chatRef = ref(null)
const messages = ref()
const titleName = ref('')
let shopId = ''
// 切换商家
const maxReadSeq = ref(0)
let sendAutoReplyStatus = 0
let shopStatus = 0
WKSDK.shared().config.provider.channelInfoCallback = async (channel) => {
  const { data } = await http.get('/p/wuKongIm/listChannelSubcribers?channelId=' + channel.channelID)
  const channelInfo = {
    logo: data.subscribers[0]?.pic,
    title: data.shopName,
    shopId: data.shopId,
    data: data.subscribers,
    channel
  }
  channelInfolineStatus.value = checkCondition(channelInfo.data)
  lineStatus.value = onLineStatus(channel.channelID)
  return channelInfo
}
const fetchChannelInfoIfNeed = (channel) => {
  if (channel) {
    channelInfo.value = WKSDK.shared().channelManager.getChannelInfo(channel)// 获取频道详情(不会触发数据源的远程获取)
    if (channelInfo.value) {
      channelInfolineStatus.value = checkCondition(channelInfo.value.data)
      lineStatus.value = onLineStatus(channel.channelID)
    } else {
      WKSDK.shared().channelManager.fetchChannelInfo(channel)
    }
  }
}
const onSelectChannel = (channel, shopName, id, maxSeq, status) => {
  shopStatus = status
  maxReadSeq.value = maxSeq
  orderList.value = []
  tabSwitch(0)
  shopId = id
  to.value = channel
  fetchChannelInfoIfNeed(channel)
  const conversation = WKSDK.shared().conversationManager.findConversation(to.value)
  if (!conversation) {
    // 如果最近会话不存在，则创建一个空的会话
    WKSDK.shared().conversationManager.createEmptyConversation(to.value)
  }
  if (status === 2 || status === 3) {
    titleName.value = '店铺已下线'
  } else {
    titleName.value = shopName
  }
  messages.value = []
  pullLast() // 拉取最新消息

  const time = setTimeout(() => {
    getRecentBrowse(id) // 获取最近浏览商品
    clearTimeout(time)
  }, 100)
}

/**
 * 获取我的订单列表
 */
const size = 10 // 我的订单 每页显示多少条
const getOrderList = (shopId) => {
  const params = {
    current: orderCurrent,
    size,
    status: 0,
    shopId,
    orderName: '',
    orderTimeStatus: '',
    orderType: '',
    orderNumber: '',
    orderMold: -1
  }
  http.get('/p/myOrder/myOrderSearch', { params }).then(({ data }) => {
    data.records.forEach((order) => {
      order.useScoreTotal = 0
      order.orderItemDtos.forEach((orderItem) => {
        if (orderItem.useScore) {
          order.useScoreTotal += orderItem.useScore
        }
        orderItem.status = order.status
      })
    })

    if (orderList.value.length >= 1) {
      orderList.value = orderList.value.concat(data.records)
      const obj = {}

      orderList.value = orderList.value.reduce((cur, next) => {
        (obj[next.orderNumber] ? '' : obj[next.orderNumber] = true) && cur.push(next)
        return cur
      }, []) // 设置cur默认类型为数组，并且初始值为空的数组
    } else {
      orderList.value = [...data.records]
    }
    orderPages = data.pages
  })
}

// 获取最近浏览信息
const getRecentBrowse = (shopId) => {
  // 最近浏览功能
  http({
    method: 'get',
    url: '/p/wuKongIm/recentBrowse',
    params: {
      current: 1,
      size: 3,
      shopId
    }
  }).then(({ data }) => {
    data.forEach(item => {
      item.orderType = item.prodType
      item.pic = checkFileUrl(item.pic)
    })
    reBrowseList.value = data
  })
}
// 拉取当前会话最新消息
const pulldowning = ref(false) // 下拉中
const pulldownFinished = ref(false) // 下拉完成
let lastMessageSeq
const pullLast = async () => {
  pulldowning.value = true
  pulldownFinished.value = false
  const msgs = await WKSDK.shared().chatManager.syncMessages(to.value, {
    limit: 15,
    startMessageSeq: 0,
    endMessageSeq: 0,
    pullMode: PullMode.Up
  })
  pulldowning.value = false
  lastMessageSeq = msgs[msgs.length - 1]?.messageSeq || msgs[msgs.length - 2]?.messageSeq || 0// 最后一条消息可能是商品链接即取倒数第二条
  if (msgs && msgs.length > 0) {
    msgs.forEach((m) => {
      messages.value.push(m)
    })
  }
  scrollBottom()
}

// 同步自己业务端的频道消息列表
WKSDK.shared().config.provider.syncMessagesCallback = async (channel, opts) => {
  const resultMessages = []
  const limit = 20
  const { data } = await http.post('/p/wuKongIm/channel/messageSync', {
    channel_id: channel.channelID,
    channel_type: channel.channelType,
    start_message_seq: opts.startMessageSeq,
    end_message_seq: opts.endMessageSeq,
    pull_mode: opts.pullMode,
    limit
  })
  const messageList = data && data.messages
  sendStatus = messageList.length > 0 ? !isTimestampToday(messageList[messageList.length - 1].timestamp * 1000) : true

  if (messageList) {
    messageList.forEach((msg) => {
      const message = Convert.toMessage(msg)
      message.content.text = JSON.parse(message.content.text)
      message.timeStr = util.tsToDate(
        message.timestamp * 1000,
        'M月D日 h:m'
      )
      resultMessages.push(message)
    })
    resultMessages.length > 0 && resultMessages.reduce((prev, cur) => {
      // 将时间更换为某某月某某日 要是是当天即去掉月日
      const now = util.tsToDate(prev.timestamp * 1000, 'M月D日 h:m')
      const next = util.tsToDate(cur.timestamp * 1000, 'M月D日 h:m')
      if (
        now.slice(0, now.indexOf(' ')) ===
            next.slice(0, next.indexOf(' '))
      ) {
        cur.timeStr = util.tsToDate(cur.timestamp * 1000, 'h:m')
      }

      // 历史记录进行时间段显示判断
      if (resultMessages.length > 2) {
        const timeFlag = timeBeApart(prev.timestamp * 1000, cur.timestamp * 1000)
        if (timeFlag) {
          delete cur.timeStr
        }
      }
      return cur
    })
  }
  let obj
  if (route.query.prodId && shopId == route.query.shopId) {
    obj = await sendProd(route.query.prodId, 1)
    resultMessages.push(obj)
  }
  if (route.query.orderNumber && shopId == route.query.shopId) {
    obj = await sendProd(route.query.orderNumber, 2)
    resultMessages.push(obj)
  }

  return resultMessages
}
let obj = {}
let prodInfo = {}
const sendProd = async (id, type) => {
  // type 1 = 商品链接  type 2 = 订单链接
  const { data } = await http.get(type === 1 ? '/prod/prodInfo?prodId=' + id : '/p/myOrder/orderDetail?orderNumber=' + id)
  if (type === 1) {
    prodInfo = {
      imgs: data.pic,
      prodId: data.prodId,
      prodName: data.prodName,
      skuName: data.skuName,
      price: data.price,
      shopId: data.shopId ? data.shopId : 1,
      orderType: data.prodType,
      actualTotal: data.price,
      msgType: 3
    }
  } else {
    const orderItem = data.orderItemDtos[0]
    prodInfo = {
      imgs: orderItem.pic,
      prodId: orderItem.prodId,
      orderNumber: route.query.orderNumber,
      skuName: orderItem.skuName,
      prodName: orderItem.prodName,
      price: data.actualTotal,
      shopId: orderItem.shopId ? Number(orderItem.shopId) : 1,
      orderType: data.orderType,
      actualTotal: data.actualTotal,
      useScore: data.orderScore,
      status: data.status,
      orderFlag: true, // 订单判断
      msgType: 3
    }
  }
  obj = {
    content: { text: { prodInfo } },
    timeStr: util.tsToDate(new Date().getTime(), 'M月D日 h:m'),
    timestamp: new Date().getTime()
  }
  return obj
}
const getMessageText = (m) => {
  if (m instanceof Message) {
    const streams = m.streams
    let text = ''
    if (m.content instanceof MessageText) {
      const messageText = m.content
      text = messageText.text.msg || ''
    }
    if (streams && streams.length > 0) {
      for (const stream of streams) {
        if (stream.content instanceof MessageText) {
          const messageText = stream.content
          text = text + (messageText.text.msg || '')
        }
      }
    }
    return text
  }

  return '未知消息'
}
const pullDown = async () => {
  if (messages.value.length == 0) {
    return
  }
  const firstMsg = messages.value[0]
  if (messages.value[0].messageSeq == 1 || !messages.value[0].messageSeq) {
    pulldownFinished.value = true
    return
  }
  const limit = 15
  const msgs = await WKSDK.shared().chatManager.syncMessages(to.value, {
    limit,
    startMessageSeq: firstMsg.messageSeq - 1,
    endMessageSeq: 0,
    pullMode: PullMode.Down
  })

  if (msgs[msgs.length - 1].content.text.prodInfo) {
    msgs.pop()
  }
  if (msgs.length < limit) {
    pulldownFinished.value = true
  }
  if (msgs && msgs.length > 0) {
    msgs.reverse().forEach((m) => {
      messages.value.unshift(m)
    })
  }
  nextTick(function () {
    const chat = chatRef.value
    const firstMsgEl = document.getElementById(firstMsg.clientMsgNo)
    if (firstMsgEl) {
      chat.scrollTop = firstMsgEl.offsetTop
    }
  })
}

const handleScroll = (e) => {
  const targetScrollTop = e.target.scrollTop
  if (targetScrollTop <= 250) { // 下拉
    if (pulldowning.value || pulldownFinished.value) {
      return
    }
    pulldowning.value = true
    pullDown().then(() => {
      pulldowning.value = false
    }).catch(() => {
      pulldowning.value = false
    })
  }
}
let messageStatusListener
const sendIssues = async (content, issues, channelId) => {
  if (shopStatus === 2 || shopStatus === 3 || shopStatusArr.includes(shopId)) {
    ElMessage.warning('商家下线')
    return
  }
  WKSDK.shared().chatManager.removeMessageStatusListener(messageStatusListener)
  const setting = Setting.fromUint8(0)
  const msgObj = JSON.stringify({ msg: issues, msgType: 1 })
  const sendContent = new MessageText(msgObj)
  WKSDK.shared().chatManager.send(sendContent, to.value, setting)
  messageStatusListener = (ack) => {
    if (ack.reasonCode === 1) {
      http.post('/p/wuKongIm/sendAutoReplyContent', { channelId, content: JSON.stringify({ msg: content, msgType: -1 }) })
    }
  }
  WKSDK.shared().chatManager.addMessageStatusListener(messageStatusListener)
}
// 判断是否当天的信息
const isTimestampToday = (timestamp) => {
  // 转换为Date对象
  const date = new Date(timestamp)

  // 获取当前日期的年、月、日
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth()
  const currentDay = currentDate.getDate()

  // 获取给定时间戳的年、月、日
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate()

  // 判断是否为当天
  return currentYear === year && currentMonth === month && currentDay === day
}
onUnmounted(() => {
  WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener)
  WKSDK.shared().chatManager.removeMessageListener(messageListener)
  WKSDK.shared().chatManager.removeCMDListener(cmdListener)
  WKSDK.shared().chatManager.removeMessageStatusListener(messageStatusListener)
  WKSDK.shared().disconnect()
})
const onLineStatus = (channel) => {
  if (shopStatus === 2 || shopStatus === 3 || shopStatusArr.includes(shopId)) {
    titleName.value = '店铺已下线'
    return 0
  }
  const index = onlineArray.findIndex(obj => Object.keys(obj)[0] === channel)
  if (!onlineArray[index]) {
    return channelInfolineStatus.value ? 1 : 0
  }
  return (onlineArray[index][channel] !== '0') ? 1 : 0
}
const checkCondition = (data) => {
  const filteredData = data.filter(item => item.sendUserType !== 0 && item.isWhiteListUser === 1)
  // 检查所有筛选项的isOnline是否都为1
  const result = filteredData.every(item => item.isOnline === 1)
  return result
}
const channelInfo = ref()
const lineStatus = ref(null)

const getChannelInfo = (m, temp) => {
  channelInfo.value = WKSDK.shared().channelManager.getChannelInfo(m.channel)// 获取频道详情(不会触发数据源的远程获取)
  let info = channelInfo.value.data.find((item) => m.fromUID === item.uid)
  if (!info) {
    info = channelInfo.value.data[0] // 客服被删除使用超管的信息
  }
  if (info) {
    return info[temp]
  }
}
const { proxy } = getCurrentInstance()
const channelInfoUpdate = () => {
  proxy.$forceUpdate()
}
// 监听cmd消息
const shopStatusArr = []
const onlineArray = []
const cmdListener = async (msg) => {
  if (isJSON(msg.content.contentObj.content)) {
    msg.content.contentObj.content = JSON.parse(msg.content.contentObj.content)
    if (msg.content.contentObj.content.type === -3) {
      maxReadSeq.value = msg.content.contentObj.content.content// 已读的最大序列号
    }
  }
  if (msg.content.contentObj?.cmd === 'onlineUpdate') {
    const parts = msg.content.contentObj.param.split('-')
    const channelId = msg.channel.channelID
    const obj = { [channelId]: parts[1] }
    if (parts[1] === '1') {
      updateOnlineArr(channelId, obj)
    } else {
      http.post('/p/wuKongIm/updateChannel', { channelId }).then(({ data }) => {
        if (data.uid === null) {
          updateOnlineArr(channelId, obj)
        }
      })
    }
  }
  if (msg.content.contentObj?.cmd === 'shopStatus') {
    const parts = msg.content.contentObj.param.split('-')
    shopStatusArr.push(Number(parts[0]))
    lineStatus.value = onLineStatus(to.value.channelID)
  }
}
const updateOnlineArr = (channelId, obj) => {
  const existingDataIndex = onlineArray.findIndex(item => {
    return item[channelId] !== undefined
  })
  if (existingDataIndex !== -1) {
    if (onlineArray[existingDataIndex][channelId] !== obj[channelId]) {
      // 新值与原先的值不同，替换原先的值
      onlineArray[existingDataIndex] = obj
    }
  } else {
    onlineArray.push(obj)
  }
  lineStatus.value = onLineStatus(channelId)
}

</script>
<style lang="scss" scoped>
@use "index";
</style>
